module client.LogicServerClient;

import std.stdio;
import msgtrans;
import std.random;
import hunt.logging;
import core.thread;
import message.Constants;


/**
 * LogicServer长连接对象
 */
class LogicServerClient {

  private __gshared LogicServerClient _instance;

  private MessageTransportClient[] _forwardClientMap;

  private uint _size = 0;

  static public LogicServerClient getInstance()
  {
    if (_instance is null)
    {
      _instance = new LogicServerClient();
    }
    return _instance;
  }

  public void addForwardClient(string id , MessageTransportClient client)
  {
    _forwardClientMap ~= client;
   // multiSort!("a.id < b.id", SwapStrategy.unstable)(_forwardClientMap);
    _size += 1;
  }

  public MessageTransportClient getForwardClient()
  {
    MessageTransportClient client = null;

    auto rnd = Random(unpredictableSeed);
    auto rand = uniform(0, _size, rnd);
    synchronized(this){
      client =  _forwardClientMap[rand];
      if (client.isClosed)
      {
        logInfo("MessageTransportClient closed!!!!!!");
        while (true)
        {
          client.connect();
          logInfo("isConnected :%s",client.isConnected );
          if(client.isConnected)
          {
            client.send(new MessageBuffer(MESSAGE.CMD_REGISTER_GATESERVER , []));
            break;
          }
          Thread.sleep(2.seconds);
        }
      }
    }
    return client;
  }
}

